package com.dt.common.validation.definition;

import java.util.regex.PatternSyntaxException;

import com.dt.common.validation.annotation.Pattern;
import com.dt.common.validation.exception.BuildingException;
import com.dt.common.validation.impl.DefaultValidationDefinition;
import com.dt.common.validation.itf.ConstraintValidation;
import com.dt.common.validation.itf.ValidationContext;

public class PatternDefinition extends DefaultValidationDefinition {
	private java.util.regex.Pattern pattern;

	public PatternDefinition() {
		this.name = Pattern.class.getSimpleName();
	}

	public void setExp(String exp, boolean caseSensitive) {
		try {
			if (caseSensitive) {
				pattern = java.util.regex.Pattern.compile(exp);
			} else {
				pattern = java.util.regex.Pattern.compile(exp, java.util.regex.Pattern.CASE_INSENSITIVE);
			}

		} catch (PatternSyntaxException e) {
			throw new BuildingException("Invalid regular expression.", e);
		}
	}

	@Override
	public ConstraintValidation buildValidation() {
		final java.util.regex.Pattern pattern_ = pattern;
		return new ConstraintValidation() {

			@Override
			public boolean isValid(ValidationContext context, Object objectValue, Object propertyValue) {
				if (propertyValue == null) {
					return true;
				}

				if (propertyValue instanceof String) {
					return pattern_.matcher((String) propertyValue).matches();
				}
				return false;
			}
		};

	}

}
